/*
 * @Date         : 2022-06-10 09:53:24
 * @LastEditors  : zu1662
 * @LastEditTime : 2024-05-24 14:48:36
 * @Description  : User Controller
 *
 * Copyright © 2022 by zu1662, All Rights Reserved.
 */
import {
  Controller,
  HttpCode,
  HttpStatus,
  Post,
  Query,
  Body,
  Get,
  InternalServerErrorException,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Response } from 'src/utils/response/response.decorator';
import { IResponse } from 'src/utils/response/response.interface';
import { PaginationService } from 'src/utils/pagination/service/pagination.service';
import { UserService } from './user.service';
import { UserListDto } from './dto/user.list.dto';
import { AuthAdminJwtGuard } from 'src/auth/auth.decorator';
import { UserListSerialization } from './serialization/user.list.serialization';
import { UserUpdateDto } from './dto/user.update.dto';
import { DebuggerService } from 'src/debugger/service/debugger.service';
import { ENUM_STATUS_CODE_ERROR } from 'src/utils/error/error.constant';

@ApiTags('User')
@Controller({
  version: '1',
  path: 'user',
})
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly paginationService: PaginationService,
    private readonly debuggerService: DebuggerService
  ) {}

  // 获取所有用户列表
  @Response('user.list')
  @AuthAdminJwtGuard()
  @HttpCode(HttpStatus.OK)
  @Get('/list')
  async list(@Query() queryParams: UserListDto): Promise<IResponse> {
    const { page, perPage, search, sort, availableSearch, availableSort, ...otherParams } =
      queryParams;
    const skip: number = await this.paginationService.skip(page, perPage);
    // 获取分页，排序数据
    const result = await this.userService.findAll({
      skip,
      page,
      perPage,
      sort,
      search,
      availableSearch,
      filters: otherParams,
    });
    // 总条数
    const totalData = result.totalData;
    // 根据总条数分页
    const totalPage: number = await this.paginationService.totalPage(totalData, perPage);
    const userData: UserListSerialization[] = await this.userService.serializationList(result.data);
    return {
      totalData,
      totalPage,
      currentPage: page,
      perPage,
      availableSearch,
      availableSort,
      data: userData,
    };
  }

  // 更新用户信息
  @Response('user.update')
  @AuthAdminJwtGuard()
  @HttpCode(HttpStatus.OK)
  @Post('/update')
  async update(@Body() body: UserUpdateDto): Promise<IResponse> {
    try {
      return await this.userService.updateUser(body);
    } catch (err: any) {
      this.debuggerService.error('update try catch', 'UserController', 'update', err);

      throw new InternalServerErrorException({
        statusCode: ENUM_STATUS_CODE_ERROR.UNKNOWN_ERROR,
        message: 'http.serverError.internalServerError',
      });
    }
  }
}
